//
//  XMN_ReadViewController.m
//  B段项目
//
//  Created by dllo on 15/11/3.
//  Copyright © 2015年 谢美娜. All rights reserved.
//

#import "XMN_ReadViewController.h"
#import "XMN_ReadScroll.h"
#import "XMN_ReadList.h"
#import "XMN_ReadCell.h"
#import "XMN_ReadTypeDetailViewController.h"
#import "XMN_ReadDetailViewController.h"

@interface XMN_ReadViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate>
@property(nonatomic, strong)UIScrollView *scrollView;
@property(nonatomic, strong)UIPageControl *pageControl;
@property(nonatomic, strong)UICollectionView *readCollectionView;
@property(nonatomic, strong)NSMutableArray *scrollViewArray;
@property(nonatomic, strong)NSMutableArray *listArray;
@property(nonatomic, strong)UIImageView *writeImageView;
//@property(nonatomic, strong)MBProgressHUD *HUD;

@property(nonatomic, strong)XMN_ProgressHUD *HUD;
@end

@implementation XMN_ReadViewController

-(void)loadView{
    [super loadView];
    
    //初始化数组
    _scrollViewArray = [NSMutableArray array];
    _listArray = [NSMutableArray array];
    
    //请求数据
    [self getDataByURLString];
    
    //滚动视图
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(10 * FitWidth, 10 * FitHeight, ScreenWidth - 20 * FitWidth, 140 * FitHeight)];
    _scrollView.contentOffset = CGPointMake(ScreenWidth - 20 * FitWidth, 0);
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.delegate = self;
    _scrollView.pagingEnabled = YES;
    [self.view addSubview:_scrollView];
    
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    
    //初始化collectionView;
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(111 * FitWidth, 105 * FitHeight);
    flowLayout.minimumLineSpacing = 10 * FitHeight;
    flowLayout.minimumInteritemSpacing = 10 * FitWidth;
    flowLayout.sectionInset = UIEdgeInsetsMake(10 * FitWidth, 10 * FitHeight, 10 *FitWidth, 10 * FitHeight);
    
    _readCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 150 * FitHeight, ScreenWidth, 358 * FitHeight) collectionViewLayout:flowLayout];
    [_readCollectionView NightWithType:UIViewColorTypeNormal];
    _readCollectionView.delegate = self;
    _readCollectionView.dataSource = self;
    _readCollectionView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_readCollectionView];
    [_readCollectionView registerClass:[XMN_ReadCell class] forCellWithReuseIdentifier:@"read"];
    
    _writeImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10 * FitWidth, _readCollectionView.frame.origin.y + _readCollectionView.frame.size.height, ScreenWidth - 20 * FitWidth, 85 * FitHeight)];
    _writeImageView.image = [UIImage imageNamed:@"XMN_Writing"];
    _writeImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *writeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(writingAction)];
    [_writeImageView addGestureRecognizer:writeTap];
    [self.view addSubview:_writeImageView];
    _writeImageView.backgroundColor = [UIColor redColor];
    
    UILabel *writeLabel = [[UILabel alloc]initWithFrame:CGRectMake(5 * FitWidth, 55 * FitHeight, ScreenWidth - 30 * FitWidth, 25 * FitHeight)];
    writeLabel.textColor = [UIColor whiteColor];
    writeLabel.layer.masksToBounds = YES;
    writeLabel.layer.cornerRadius = 5 * FitWidth;
    writeLabel.font = [UIFont fontWithName:@"Zapfino" size:15];
    writeLabel.text = @"自由写作 Writing";
    [_writeImageView addSubview:writeLabel];
    //初始化小白点
    _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(280 * FitWidth, 130 * FitHeight, 100 * FitWidth, 10 * FitHeight)];
    [self.view addSubview:_pageControl];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"阅读";
    
    _HUD = [[XMN_ProgressHUD alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, Height)];
    _HUD.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
    _HUD.XMN_label.text = @"Waiting...";
    [self.view addSubview:_HUD];
}

#pragma mark - 数据解析
-(void)getDataByURLString{
    [HTTPMethod getDataByString:@"http://api2.pianke.me/read/columns" BODYDic:[ChangeString changeStringToDictionary:@"client=2&auth=W8A7Rym2z8m3lDC8hwH8XikTJxQMCqYOXe8zo6Wj0xcWP22NBKTh5Z7Pg"] WithDataBlock:^(id data) {
//        NSLog(@"%@", data);
        NSArray *scrollViewArr = [[data objectForKey:@"data"] objectForKey:@"carousel"];
        for (NSDictionary *dic in scrollViewArr) {
            XMN_ReadScroll *scroll = [[XMN_ReadScroll alloc]init];
            [scroll setValuesForKeysWithDictionary:dic];
            [_scrollViewArray addObject:scroll];
        }
        //给scrollView添加图片
        _scrollView.contentSize = CGSizeMake((ScreenWidth - 20 * FitWidth) * (_scrollViewArray.count + 2), 140 * FitHeight);
        for (NSInteger i = 0; i < _scrollViewArray.count + 2; i++) {
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(_scrollView.frame.size.width * i, 0, _scrollView.frame.size.width, _scrollView.frame.size.height)];
            imageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *imageViewTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageViewTapAction:)];
            [imageView addGestureRecognizer:imageViewTap];
            if (i == 0) {
                [imageView sd_setImageWithURL:[NSURL URLWithString:[[_scrollViewArray objectAtIndex:_scrollViewArray.count - 1] img]]];
                [imageView sd_setImageWithURL:[NSURL URLWithString:[[_scrollViewArray objectAtIndex:_scrollViewArray.count - 1] img]] placeholderImage:[UIImage imageNamed:@"XMN_Read_Scroll"]];
            }
            if (i == _scrollViewArray.count + 1) {
                [imageView sd_setImageWithURL:[NSURL URLWithString:[[_scrollViewArray objectAtIndex:0] img]]];
                [imageView sd_setImageWithURL:[NSURL URLWithString:[[_scrollViewArray objectAtIndex:0] img]] placeholderImage:[UIImage imageNamed:@"XMN_Read_Scroll"]];
            }if (i < _scrollViewArray.count + 1 && i > 0) {
                [imageView sd_setImageWithURL:[NSURL URLWithString:[[_scrollViewArray objectAtIndex:i - 1] img]]];
                [imageView sd_setImageWithURL:[NSURL URLWithString:[[_scrollViewArray objectAtIndex:i - 1] img]] placeholderImage:[UIImage imageNamed:@"XMN_Read_Scroll"]];
            }
            [_scrollView addSubview:imageView];
        }
        
        _pageControl.numberOfPages = _scrollViewArray.count;
        _pageControl.pageIndicatorTintColor = [UIColor whiteColor];
        _pageControl.currentPageIndicatorTintColor = [UIColor grayColor];
        
        NSArray *listArr = [[data objectForKey:@"data"] objectForKey:@"list"];
        for (NSDictionary *dic in listArr) {
            XMN_ReadList *list = [[XMN_ReadList alloc]init];
            [list setValuesForKeysWithDictionary:dic];
            [_listArray addObject:list];
        }
        [_readCollectionView reloadData];
        [_HUD removeFromSuperview];
    }];
}

#pragma mark - collectionView的相关设置
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    XMN_ReadCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"read" forIndexPath:indexPath];
    XMN_ReadList *list = [_listArray objectAtIndex:indexPath.row];
    [cell.backImageView sd_setImageWithURL:[NSURL URLWithString:list.coverimg]];
    [cell.backImageView sd_setImageWithURL:[NSURL URLWithString:list.coverimg] placeholderImage:[UIImage imageNamed:@"XMN_Read_Collection"]];
    cell.label.text = [NSString stringWithFormat:@"%@ %@", list.name, list.enname];
    return cell;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _listArray.count;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    XMN_ReadTypeDetailViewController *readTypeVC = [[XMN_ReadTypeDetailViewController alloc]init];
    [self.navigationController pushViewController:readTypeVC animated:YES];
    readTypeVC.list = [_listArray objectAtIndex:indexPath.row];
}

#pragma mark - scrollView代理方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    _pageControl.currentPage = _scrollView.contentOffset.x / (ScreenWidth - 20 * FitWidth) - 1;
    if (scrollView.contentOffset.x > (_scrollViewArray.count + 1) * (ScreenWidth - 20 * FitWidth)) {
        _scrollView.contentOffset = CGPointMake((ScreenWidth - 20 * FitWidth), 0);
        _pageControl.currentPage = 0;
    }
    if (scrollView.contentOffset.x < 0) {
        _scrollView.contentOffset = CGPointMake((ScreenWidth - 20 * FitWidth) * _scrollViewArray.count, 0);
        _pageControl.currentPage = _scrollViewArray.count - 1;
    }
}

#pragma mark - 定时器
-(void)timerAction{
    if (_scrollView.contentOffset.x == (_scrollViewArray.count + 1) * (ScreenWidth - 20 * FitWidth))
    {
        [_scrollView setContentOffset:CGPointMake((ScreenWidth - 20 * FitWidth), 0)];
    }
    else if(_scrollView.contentOffset.x == 0)
    {
        [_scrollView setContentOffset:CGPointMake((ScreenWidth - 20 * FitWidth) * _scrollViewArray.count, 0)];
    }
    else{
        [_scrollView setContentOffset:CGPointMake(_scrollView.contentOffset.x + (ScreenWidth - 20 * FitWidth), 0) animated:YES];
    }
}

#pragma mark - 手势
-(void)writingAction{
    XMN_ReadTypeDetailViewController *readTypeVc = [[XMN_ReadTypeDetailViewController alloc]init];
    [self.navigationController pushViewController:readTypeVc animated:YES];
    readTypeVc.whichOne = 1;
    readTypeVc.titleString = @"自由写作";
}

-(void)imageViewTapAction:(UIScrollView *)scrollView{
    CGPoint point = _scrollView.contentOffset;
    XMN_ReadDetailViewController *readDvc = [[XMN_ReadDetailViewController alloc]init];
    [self.navigationController pushViewController:readDvc animated:YES];
    NSString *str = @"";
    CGFloat index = point.x / 355 * FitWidth;
    if (index > 1 && index < 3) {
        str = [[NSString stringWithFormat:@"%@", [[_scrollViewArray objectAtIndex:1] url]] substringFromIndex:17];
    }
    if (index > 2 && index < 4) {
        str = [[NSString stringWithFormat:@"%@", [[_scrollViewArray objectAtIndex:2] url]] substringFromIndex:17];
    }
    if ((index > 0 && index < 2) || (index > 3 && index < 5)) {
        str = [[NSString stringWithFormat:@"%@", [[_scrollViewArray objectAtIndex:0] url]] substringFromIndex:17];
    }
    readDvc.idString = str;
    readDvc.titleString = @"null";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
